﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using FrameConstructor;

namespace TetrisShape
{
    public class Field
    {
        bool flag = true;
        private List<Shape> ShapeStorage = new List<Shape>();
        public List<Shape> ReturnShapeStorage { get { return ShapeStorage; } }

        Render rd = new Render();
        Frame fr = new Frame();
        Block bl = new Block();

        public Frame SetGameField()
        {
            if (ShapeStorage.Count == 0)
            {
                Console.Clear();
            }
            Console.ForegroundColor = ConsoleColor.White;
            fr.SetFrame(20, 20, 31, 41);
            return fr;
        }

        public void Move()
        {
            Shape sh = new Shape();
            sh.CreateRandomShape(SetGameField(), sh);
            int i = 0;
            do
            {
                rd.ClearShape(sh, fr);
                rd.PrintShape(sh);
                bl.DoStep(sh);
                i++;
            } while (IsPositionFree(sh));
            ShapeStorage.Add(sh);
        }

        public void StartMoveShape()
        {
            do
            {
                Move();
            } while (flag);
        }

        public bool IsPositionFree(Shape sh)
        {
            if (ShapeStorage.Count != 0)
            {
                foreach (Shape currentShape in sh.ReturnShape)
                {
                    foreach (Block currentBlock in sh.ReturnBlock)
                    {
                        foreach (Shape shapeInStorage in ShapeStorage)
                        {
                            foreach (Block blockInStorage in shapeInStorage.ReturnBlock)
                            {
                                if (blockInStorage.Y == fr.StartY+2)
                                {
                                    flag = false;
                                    return false;
                                }
                                if (currentBlock.X == blockInStorage.X && currentBlock.Y == blockInStorage.Y - 1)
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (Shape shape in sh.ReturnShape)
                {
                    foreach (Block block in sh.ReturnBlock)
                    {
                        if (Console.CursorTop == fr.StartY + 19)
                            return false;
                    }
                }
            }
            return true;
        }
    }
}
